package morphage.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;

import javax.swing.JViewport;
import morphage.engine.ImageManager;
import morphage.engine.OperationLayer;
import morphage.engine.Pipeline;

public class AppRenderViewPanel extends JViewport implements ImageObserver
{
	private static final long 		serialVersionUID 	= 1L;
	
	public static final int           CENTER_VIEW         = 0;
  public static final int           LEFT_VIEW           = 1;
  public static final int           RIGHT_VIEW          = 2;
	
	private AppRenderViewListener      m_listener;
	private int                        m_viewSide;

	public AppRenderViewPanel(int viewSide)
	{
	  m_viewSide    = viewSide;
	  
		setOpaque( true );
		setPreferredSize( new Dimension(200, 300) );
		m_listener       = new AppRenderViewListener( this );
		addMouseWheelListener( m_listener );
		addMouseListener( m_listener );
		addMouseMotionListener( m_listener );
	}
	public void paint(Graphics g)
	{
	  super.paint(g);
	  Image image = null;
	  int id = PipelineTabPane.getCurrentOperationId();
	  if( id == PipelineTabPane.ORIGINAL_IMAGE || id == PipelineTabPane.RESULT_IMAGE)
	  {
	    switch( m_viewSide )
	    {
	    case LEFT_VIEW:
	      image = ImageManager.getFirstImage();
	      break;
	    case RIGHT_VIEW:
	      image = ImageManager.getLastImage();
	      break;
	    case CENTER_VIEW:
	      if( id == PipelineTabPane.ORIGINAL_IMAGE )
	        image = ImageManager.getFirstImage();
	      else
	        image = ImageManager.getCurrentResult();
	      break;
	    }
	    if( image != null )
	    {
	      g.drawImage(image, 0, 0, getWidth(), getHeight(), this );
	    }
	    else
	    {
	      g.setColor(Color.WHITE);
	      g.fillRect(0, 0, getWidth(), getHeight());
	    }
	  }
	  else
	  {
	    OperationLayer op = Pipeline.getDefaultPipeline().getOperationLayer(id);
	    assert( op != null );
	    switch( m_viewSide )
	    {
	    case LEFT_VIEW:
	      op.paintFirst(g, getWidth(), getHeight(), this);
	      break;
	    case RIGHT_VIEW:
	      op.paintLast(g, getWidth(), getHeight(), this);
	      break;
	    case CENTER_VIEW:
	      op.paintIntermediate(g, getWidth(), getHeight(), this);
	      break;
	    }	    
	  } 
	}
	public int getViewSide(){ return m_viewSide; }
	
  public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
  {
    if( infoflags == ALLBITS)
    {
      this.repaint();
      return false;
    }
    else return true;
  }
}
